package com.nys.cqhttp.message.factory.impl;

import cn.hutool.http.HttpUtil;
import com.alibaba.fastjson.JSONObject;
import com.nys.cqhttp.mapper.ApplyLogMapper;
import com.nys.cqhttp.message.factory.IMessageHandler;
import com.nys.cqhttp.model.ApplyLog;
import com.nys.cqhttp.model.ApplyLogExample;
import com.nys.cqhttp.model.Massage;
import com.nys.cqhttp.param.Context;
import com.nys.cqhttp.param.MessageParam;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;
import java.util.*;

/**
 * DirectUrlMessageHandler
 *
 * @author nysheng
 * @version 1.0.0
 * @description 群管理
 * @date 2021/12/28 19:53
 */
@Slf4j
@Component
public class GroupAdminMessageHandler implements IMessageHandler {
  private static String at = "[CQ:at,qq=";
  private static String at1 = "]";
  @Autowired private ApplyLogMapper applyLogMapper;
  private static GroupAdminMessageHandler groupAdminMessageHandler;

  @PostConstruct
  public void init() throws Exception {
    groupAdminMessageHandler = this;
    applyLogMapper = this.applyLogMapper;
  }

  @Override
  public List<String> listHandler(Massage messagePojo, Context context) {
    return Arrays.asList(handler(messagePojo, context));
  }

  public Map<String, Object> getGroupMemberInfo(Map<String, Object> map, String url) {
    String post = HttpUtil.post(url + "/get_group_member_info", map);
    Map<String, Object> data =
        JSONObject.parseObject(
            JSONObject.parseObject(post, Map.class).get("data").toString(), Map.class);
    return data;
  }

  @Override
  public String handler(Massage messagePojo, Context context) {
    try {
      MessageParam messageParam = context.getMessageParam();
      String message = messageParam.getMessage();
      String senderId = messageParam.getSenderId();
      String selfId = messageParam.getSelfId();
      String groupId = messageParam.getGroupId();
      String url = messageParam.getUrl();
      Map<String, Object> map = new HashMap<>();
      map.put("group_id", groupId);
      map.put("user_id", senderId);
      if (!message.equals("invite")) {
        if (!message.equals("add")) {
          if (getGroupMemberInfo(map, url).get("role").toString().equals("member")) {
            return at + messageParam.getSenderId() + at1 + "你不是管理员";
          }
        }
        map.put("user_id", selfId);
        if (getGroupMemberInfo(map, url).get("role").toString().equals("member")) {
          return at + messageParam.getSenderId() + at1 + "机器人不是管理员";
        }
      }
      if (message.contains("禁")) {
        String[] split = message.split("\\*");
        String s = message.substring(12, messageParam.getMessage().indexOf("]"));
        log.info(s);
        map.put("user_id", s);
        if (!getGroupMemberInfo(map, url).get("role").toString().equals("member")) {
          return "被禁言人是管理员,不可操作!";
        }
        int i = Integer.parseInt(split[1]);
        map.put("duration", Integer.parseInt(split[1]) * 60);
        HttpUtil.post(url + "/set_group_ban", map);
        return "禁言成功!";
      } else if (message.contains("解")) {
        String s = message.substring(12, messageParam.getMessage().indexOf("]"));
        map.put("user_id", s);
        if (!getGroupMemberInfo(map, url).get("role").toString().equals("member")) {
          return "被解禁人是管理员,不可操作!";
        }
        map.put("duration", 0);
        HttpUtil.post(url + "/set_group_ban", map);
        return "解禁成功!";
      } else if (message.contains("踢")) {
        String[] split = message.split("\\[CQ:at,qq=");
        log.info(split[1]);
        String str1 = "";
        String str2 = "";
        for (int i = 1; i < split.length; i++) {
          String substring = split[i].substring(0, split[i].indexOf("]"));
          map.put("user_id", substring);
          if (!getGroupMemberInfo(map, url).get("role").toString().equals("member")) {
            if (StringUtils.isEmpty(str2)) {
              str2 = "失败 " + substring;
            } else {
              str2 += " " + substring;
            }
          } else {
            HttpUtil.post(url + "/set_group_kick", map);
            if (StringUtils.isEmpty(str1)) {
              str1 = "成功踢出 " + substring;
            } else {
              str1 += " " + substring;
            }
          }
        }
        return str1 + str2;
      } else if (message.equals("add")) {
        ApplyLogExample applyLogExample = new ApplyLogExample();
        ApplyLogExample.Criteria criteria = applyLogExample.createCriteria();
        criteria.andJqrQqEqualTo(selfId);
        criteria.andUserQqEqualTo(senderId);
        criteria.andGroupIdEqualTo(groupId);
        List<ApplyLog> applyLogs =
            groupAdminMessageHandler.applyLogMapper.selectByExample(applyLogExample);
        if (CollectionUtils.isNotEmpty(applyLogs)) {
          groupAdminMessageHandler.applyLogMapper.deleteByExample(applyLogExample);
        }
        ApplyLog applyLog = new ApplyLog();
        applyLog.setFlag(messageParam.getFlag());
        applyLog.setType(message);
        applyLog.setUserQq(senderId);
        applyLog.setJqrQq(selfId);
        applyLog.setGroupId(groupId);
        applyLog.setApplyDate(new Date());
        groupAdminMessageHandler.applyLogMapper.insertSelective(applyLog);

        return "有人申请进群\nQQ" + senderId + "\n验证消息:\n" + messageParam.getOperatorId() + "\n同意/拒绝申请";
      } else if (message.equals("invite")) {
        Map<String, Object> map1 = new HashMap<>();
        map1.put("flag", messageParam.getFlag());
        map1.put("type", message);
        if (Arrays.asList(messagePojo.getValue().split(",")).contains(senderId)) {
          map1.put("approve", true);
        }else{
          map1.put("approve", false);
        }
        HttpUtil.post(url + "/set_group_add_request", map1);
        return "";
      } else if (message.contains("同意申请")) {
        if (message.equals("同意申请")) {
          ApplyLogExample applyLogExample = new ApplyLogExample();
          ApplyLogExample.Criteria criteria = applyLogExample.createCriteria();
          criteria.andJqrQqEqualTo(selfId);
          //          criteria.andUserQqEqualTo(senderId);
          criteria.andGroupIdEqualTo(groupId);
          applyLogExample.setOrderByClause("apply_date DESC limit 0,1");

          List<ApplyLog> applyLogs =
              groupAdminMessageHandler.applyLogMapper.selectByExample(applyLogExample);
          if (CollectionUtils.isEmpty(applyLogs)) {
            return "无申请处理!";
          } else {
            ApplyLog applyLog = applyLogs.get(0);
            Map<String, Object> map1 = new HashMap<>();
            map1.put("flag", applyLog.getFlag());
            map1.put("type", applyLog.getType());
            map1.put("approve", true);
            HttpUtil.post(url + "/set_group_add_request", map1);
            groupAdminMessageHandler.applyLogMapper.deleteByPrimaryKey(applyLog.getId());
            return "";
          }
        } else {
          String[] split = message.split("-");
          for (int i = 1; i < split.length; i++) {
            //            String s = split[i].substring(0, messageParam.getMessage().indexOf("]"));
            ApplyLogExample applyLogExample = new ApplyLogExample();
            ApplyLogExample.Criteria criteria = applyLogExample.createCriteria();
            criteria.andJqrQqEqualTo(selfId);
            criteria.andUserQqEqualTo(split[i]);
            criteria.andGroupIdEqualTo(groupId);
            applyLogExample.setOrderByClause("apply_date DESC limit 0,1");
            List<ApplyLog> applyLogs =
                groupAdminMessageHandler.applyLogMapper.selectByExample(applyLogExample);
            if (CollectionUtils.isNotEmpty(applyLogs)) {
              ApplyLog applyLog = applyLogs.get(0);
              Map<String, Object> map1 = new HashMap<>();
              map1.put("flag", applyLog.getFlag());
              map1.put("type", applyLog.getType());
              map1.put("approve", true);
              HttpUtil.post(url + "/set_group_add_request", map1);
              return "";
            }
          }
        }
      } else if (message.contains("拒绝申请")) {
        if (message.equals("拒绝申请")) {
          ApplyLogExample applyLogExample = new ApplyLogExample();
          ApplyLogExample.Criteria criteria = applyLogExample.createCriteria();
          criteria.andJqrQqEqualTo(selfId);
          //          criteria.andUserQqEqualTo(senderId);
          criteria.andGroupIdEqualTo(groupId);
          applyLogExample.setOrderByClause("apply_date DESC limit 0,1");

          List<ApplyLog> applyLogs =
              groupAdminMessageHandler.applyLogMapper.selectByExample(applyLogExample);
          if (CollectionUtils.isEmpty(applyLogs)) {
            return "无申请处理!";
          } else {
            ApplyLog applyLog = applyLogs.get(0);
            Map<String, Object> map1 = new HashMap<>();
            map1.put("flag", applyLog.getFlag());
            map1.put("type", applyLog.getType());
            map1.put("approve", false);
            HttpUtil.post(url + "/set_group_add_request", map1);
            groupAdminMessageHandler.applyLogMapper.deleteByPrimaryKey(applyLog.getId());
            return "";
          }
        } else {
          String[] split = message.split("-");
          for (int i = 1; i < split.length; i++) {
            //            String s = split[i].substring(0, messageParam.getMessage().indexOf("]"));
            ApplyLogExample applyLogExample = new ApplyLogExample();
            ApplyLogExample.Criteria criteria = applyLogExample.createCriteria();
            criteria.andJqrQqEqualTo(selfId);
            criteria.andUserQqEqualTo(split[i]);
            criteria.andGroupIdEqualTo(groupId);
            applyLogExample.setOrderByClause("apply_date DESC limit 0,1");
            List<ApplyLog> applyLogs =
                groupAdminMessageHandler.applyLogMapper.selectByExample(applyLogExample);
            if (CollectionUtils.isNotEmpty(applyLogs)) {
              ApplyLog applyLog = applyLogs.get(0);
              Map<String, Object> map1 = new HashMap<>();
              map1.put("flag", applyLog.getFlag());
              map1.put("type", applyLog.getType());
              map1.put("approve", false);
              HttpUtil.post(url + "/set_group_add_request", map1);
              return "";
            }
          }
        }
      }
      return "";
    } catch (Exception e) {
      e.printStackTrace();
      return "格式错误";
    }
  }
}
